#!/usr/bin/env phantomjs

function showHelp(){
  console.log('Usage: <URL> [Options]  URL can start with <http://> or <https://>, default <http://>');
  console.log('Options:');
  console.log('  -o <file[:file]>      Output files');
  console.log('  -q <0~100>            Quality for render');
  console.log('  -t <timeout>          Set timeout in milliseconds');
  console.log('  -d                    Run in debug mode, in this mode, this shell will print more information');
  console.log('  -width <width>        set veiw port width');
  console.log('  -height <height>      set veiw port height');
  phantom.exit();
}

function getExtension(path){
    return path.substring(path.lastIndexOf('.') + 1, path.length);
}


var system = require('system');
var fs = require('fs');
var outputFiles=new Array();
var t = Date.now();
var debug = false;
var timeout = 20000;
var width = 300
var height = 400

if (system.args.length === 1) {
    showHelp();
}

var url = system.args[1];
outputFiles[0] = 'output.jpeg'
quality = 50
i1 = url.indexOf('http://');
i2 = url.indexOf('https://');
if( i1 != 0 && i2 != 0){
  url = 'http://' + url;
}

for( var i = 0; i < system.args.length; i++){
  arg = system.args[i]
  if(arg === '-o' && i + 1 < system.args.length){
    outputFiles = system.args[++i].split(':');
  }else if(arg === '-q' && i + 1 < system.args.length){
    quality = parseInt(system.args[++i]);
  }else if(arg === '-t' && i + 1 < system.args.length){
    timeout = parseInt(system.args[++i]);
  }else if(arg === '--width' && i + 1 < system.args.length){
    width = parseInt(system.args[++i]);
  }else if(arg === '--height' && i + 1 < system.args.length){
    height = parseInt(system.args[++i]);
  }else if(arg === '-d'){
    debug = true;
  }else if(arg === '--help' || arg === '-h'){
    showHelp();
  }
}

if(debug){
    console.log("Timeout:" + timeout + "ms")
    console.log("Quality:" + quality)
    console.log("OutputFile:")
    for(var i in outputFiles){
        console.log("  " +outputFiles[i])
    }
}

var page = require('webpage').create();
page.settings.resourceTimeout=timeout;
page.viewportSize = {
  width: width,
  height: height 
};
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36';
console.log('Loading ' + system.args[1]);
page.open(url, function(status) {
  if (status !== 'success') {
    console.log('FAIL to load [' + system.args[1] + ']');
    phantom.exit(-1)
  } else {
    var title = page.title;
    if(debug){
        console.log('Title:' + title)
    }
    for(var i in outputFiles){
        var output = outputFiles[i];
        page.render(output , {format: getExtension(output), quality: quality});
    }
    t = Date.now() - t;
    if(debug){
        console.log('Time:' + t)
    }
    phantom.exit();
  }
});
